const user = require("../sql/user");
const sql = require("../sql");
const md5 = require("md5");
const jwt = require("jsonwebtoken");

module.exports = (req, res)=>{
    const un = req.query.username;
    const pw = req.query.password;
    // 根据数据查询数据库
    sql.get({
        colObj:user,
        where:{username: un}
    }).then(data=>{
        if(data.length > 0){
            // 查到了，比对密码
            if(data[0].password === md5(pw)){
                // 密码相同，修改本条数据的登录时间
                sql.set(user, {
                    username: un, password: md5(pw)
                }, {
                    lastLoginTime: Date.now()
                }).then(()=>{
                    // res.cookie("isLogin", "ok123");
                    // req.session.isLogin = "hello ok";

                    const token = jwt.sign({
                        username: un
                    }, "杨树林er", {
                        expiresIn: 60 * 60
                    });

                    // 并响应登录成功
                    res.send({
                        code:1,
                        msg:"登录成功",
                        token
                    });
                })
            }else{
                res.send({code:2, msg:"密码不对"});
            }
        }else{
            res.send({code:0, msg:"用户名不存在"});
        }
    })
}

